﻿using d1Common.Interface;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Web.Http.Routing;

namespace d1Common.WebController
{
    public class PermissionCheckAttribute : AuthorizeAttribute
    { 

        public PermissionCheckAttribute()
        {

        }
        public string Id
        {
            get;
            set;
        }
        public int Operation
        {
            get;
            set;
        }
        protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            Authorize1Controller _controller = actionContext.ControllerContext.Controller as Authorize1Controller;
            if (_controller == null) throw new UserException("Permission只允许应用于Authorize1ControllerBase");

            if (_controller.UserId == "admin")
            {
                if (this.Operation == 0) return true;
                IDoPermissionOpt _doPermissionOpt = doServices.Instance.Do4AService.getDoPermissionOpt(this.Id, this.Operation);
                if (_doPermissionOpt != null)
                {
                    doServices.Instance.Do4AService.WriteAuditLog(_doPermissionOpt.PermissionId,
                        _doPermissionOpt.PermissionName + "_" + _doPermissionOpt.OperationName,
                        _controller.UserId, _controller.UserName, "");
                }
                return true;
            }
            IDictionary<string, IRolePermission> _permissions = doServices.Instance.Do4AService.GetRolePermissions(_controller.RoleId);
            if (_permissions == null || !_permissions.ContainsKey(this.Id))
            {
                throw new UserException("不具备访问权限");
            }
            if (this.Operation > 0)
            {
                if ((_permissions[this.Id].Operations & this.Operation) == 0)
                {
                    throw new UserException("不具备操作权限");
                }
                if (this.Operation == 0) return true;
                IDoPermissionOpt _doPermissionOpt = doServices.Instance.Do4AService.getDoPermissionOpt(this.Id, this.Operation);
                if (_doPermissionOpt != null)
                {
                    doServices.Instance.Do4AService.WriteAuditLog(_doPermissionOpt.PermissionId,
                        _doPermissionOpt.PermissionName + "_" + _doPermissionOpt.OperationName,
                        _controller.UserId, _controller.UserName, "");
                }
            }            
            return true;
        }
    }
}